//
//  MasterViewController.m
//  SAYAKA_Kitchen
//
//  Created by Rei on 13/07/20.
//  Copyright (c) 2013年 hackathon. All rights reserved.
//

#import "MasterViewController.h"
#import "DetailListViewController.h"

@interface MasterViewController () <DetailListViewControllerDelegate>{
    NSMutableArray *_tableNumbersArray;
    NSMutableArray *_newOrderFlagArray;
}
#ifdef DEBUG
@property (assign, nonatomic) int notificationCount;
#endif
@end

@implementation MasterViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title = @"テーブル一覧";
        self.clearsSelectionOnViewWillAppear = NO;
        self.contentSizeForViewInPopover = CGSizeMake(320.0, 600.0);
        
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(insertNewObject:)
                                                 name:@"RecieveOrder"
                                               object:nil];
    self.detailViewController.delegate = self;
    
    
#ifdef DEBUG
    UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd
                                                                               target:self
                                                                               action:@selector(recieveOrderTest:)];
    self.navigationItem.rightBarButtonItem = addButton;
    self.notificationCount = 0;
#endif

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#ifdef DEBUG
- (void)recieveOrderTest:(id)sender {
    NSMutableArray *items = [NSMutableArray array];
    
    NSMutableDictionary *item = [NSMutableDictionary dictionary];
    [item setObject:@"牛肉と豚肉とチキンのカレー" forKey:@"name"];
    [item setObject:@"1280" forKey:@"price"];
    [item setObject:@"12" forKey:@"num_of_items"];
    [items addObject:[item copy]];
    
    [item setObject:@"さかなカレー" forKey:@"name"];
    [item setObject:@"1000" forKey:@"price"];
    [item setObject:@"18" forKey:@"num_of_items"];
    [items addObject:[item copy]];

    [item setObject:@"鯛カレー" forKey:@"name"];
    [item setObject:@"1250" forKey:@"price"];
    [item setObject:@"8" forKey:@"num_of_items"];
    [items addObject:[item copy]];
    
    NSDictionary *userInfo = [NSDictionary dictionaryWithObjectsAndKeys:
                              [NSNumber numberWithInt:self.notificationCount] ,@"table_number",
                              items, @"items",nil];

    NSNotification *notification = [NSNotification notificationWithName:@"testOrder" object:self userInfo:userInfo];
    [[NSNotificationCenter defaultCenter] postNotification:notification];
    self.notificationCount += 1;
    if (self.notificationCount == 3) {
        self.notificationCount = 0;
    }
}
#endif

//新規注文時に呼ばれる
- (void)insertNewObject:(NSNotification *)notification
{
    if (!_tableNumbersArray) {
        _tableNumbersArray = [[NSMutableArray alloc] init];
        _newOrderFlagArray = [[NSMutableArray alloc] init];
    }
    
    int tableNumber = [[[notification userInfo] objectForKey:@"table_number"] intValue];
    BOOL isFirstOrder = YES;
    for (id number in _tableNumbersArray) {
        if (tableNumber == [number intValue]) {
            isFirstOrder = NO;
        }
    }
    
    //初回注文時のみセルを追加
    if (isFirstOrder) {
        [_tableNumbersArray insertObject:[NSNumber numberWithInteger:tableNumber] atIndex:0];
        [_newOrderFlagArray insertObject:[NSNumber numberWithBool:YES] atIndex:0];
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
        [self.tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
    } else {
        [_newOrderFlagArray replaceObjectAtIndex:tableNumber withObject:[NSNumber numberWithBool:YES]];
        [self.tableView reloadData];
    }
}

#pragma mark - Table View
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _tableNumbersArray.count;
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
    }
    
    
    int tableNumber = [[_tableNumbersArray objectAtIndex:indexPath.row] intValue];
    cell.textLabel.text = [NSString stringWithFormat:@"テーブル番号: %d", tableNumber];
    
    if ([[_newOrderFlagArray objectAtIndex:indexPath.row] boolValue]) {
        cell.detailTextLabel.text = @"new!";
        cell.detailTextLabel.textColor = [UIColor redColor];
    } else {
        cell.detailTextLabel.text = nil;
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    self.detailViewController.detailItem = [_tableNumbersArray objectAtIndex:indexPath.row];
    [_newOrderFlagArray replaceObjectAtIndex:indexPath.row withObject:[NSNumber numberWithBool:NO]];
    [self.tableView reloadData];
    [self.tableView deselectRowAtIndexPath:[self.tableView indexPathForSelectedRow] animated:YES];
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}

/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
 {
 }
 */

/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
 {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */


//データの削除処理
- (void)detailListViewController:(DetailListViewController *)detailListViewController clearOrderForNumberOfTable:(int)tableNumberIndex {
    [_tableNumbersArray removeObjectAtIndex:tableNumberIndex];
    [_newOrderFlagArray removeObjectAtIndex:tableNumberIndex];
    [self.tableView reloadData];
}
@end